package com.zbkj.crmeb.task.product.junmeng;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.crmeb.core.common.CommonResult;
import com.factory.PushWarehouseFactory;
import com.utils.dto.StoreProductQueryDto;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.zbkj.crmeb.store.dao.StoreProductDao;
import com.zbkj.crmeb.store.model.Relation;
import com.zbkj.crmeb.store.model.StoreProduct;
import com.zbkj.crmeb.store.model.StoreProductAttrValue;
import com.zbkj.crmeb.store.service.CommonStoreOrderService;
import com.zbkj.crmeb.store.service.RelationService;
import com.zbkj.crmeb.store.service.StoreProductAttrValueService;
import com.zbkj.crmeb.store.service.StoreProductService;
import com.zbkj.crmeb.task.product.junmeng.dto.WarehouseResultData;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.collections4.ListUtils;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Component
@Configuration
@Slf4j
public class WarehouseProductStockSync implements ApplicationRunner {

    @Resource
    private StoreProductDao storeProductDao;
    @Resource
    private StoreProductAttrValueService storeProductAttrValueService;
    @Resource
    private PushWarehouseFactory pushWarehouseFactory;
    @Resource
    private RelationService relationService;

    @Resource
    private StoreProductService storeProductService;

    private final static Map<Integer,String> MAP = new HashMap<>();

    private final static Map<String,String> SERVICE_MAP = new HashMap<>();

    static {
        MAP.put(285,"WL");
//        MAP.put(281,"MY");
//        MAP.put(265,"YM");
//        MAP.put(191,"CT");
//        MAP.put(176,"CT");
//        MAP.put(215,"CT");
        SERVICE_MAP.put("WL","wenLianStoreOrderServiceImpl");
        SERVICE_MAP.put("MY","myStoreOrderServiceImpl");
        SERVICE_MAP.put("YM","ymStoreOrderServiceImpl");
        SERVICE_MAP.put("YSY","ysyStoreOrderServiceImpl");
        SERVICE_MAP.put("CT","commonStoreOrderServiceImpl");

    }
    @Override
    public void run(ApplicationArguments args) throws Exception {
//        stockSync();
    }
    @XxlJob("warehouseStockSyncV2")
    public void stockSyncV2(){
        List<Relation> relationList =  relationService.list(Wrappers.<Relation>lambdaQuery().eq(Relation::getBusinessType, "WAREHOUSE_PRODUCT_STOCK"));
        if (CollectionUtils.isEmpty(relationList)){
            return;
        }
        String skuIdStr = relationList.stream().map(k -> k.getBusinessCode()).collect(Collectors.joining(","));

        CommonStoreOrderService serviceInstance = pushWarehouseFactory.getServiceInstance(SERVICE_MAP.get("WL"));
        CommonResult<List<WarehouseResultData>> listCommonResult = serviceInstance.queryOrderStockInfo(skuIdStr);
        if (null == listCommonResult || CollectionUtils.isEmpty(listCommonResult.getData())){
            return;
        }
        List<WarehouseResultData> warehouseResultDataList = listCommonResult.getData();
        Map<String, WarehouseResultData> resultMap = warehouseResultDataList.stream().collect(Collectors.toMap(WarehouseResultData::getGoodsNo, v -> v));

        for (Relation relation : relationList) {
            String businessCode = relation.getBusinessCode();
            if (!resultMap.containsKey(businessCode)) {
                continue;
            }
            WarehouseResultData warehouseResultData = resultMap.get(businessCode);
            int warehouseStock = warehouseResultData.getRemain();
            relation.setSubCode(String.valueOf(warehouseStock));
            String selfSkuId = businessCode.replaceAll("[^0-9]", "");
            List<StoreProductAttrValue> attrValueList = storeProductAttrValueService.list(Wrappers.<StoreProductAttrValue>lambdaQuery().likeRight(StoreProductAttrValue::getSelfSourceSkuId, selfSkuId));
            if (CollectionUtils.isEmpty(attrValueList)) {
                continue;
            }
            // 特殊处理
            if (attrValueList.size() <= 1) {
                StoreProductAttrValue storeProductAttrValue = attrValueList.get(0);
                updateStock(storeProductAttrValue,warehouseStock);
                continue;
            }
            Map<String, StoreProductAttrValue> sttrMap = new HashMap<>();
            for (StoreProductAttrValue storeProductAttrValue : attrValueList) {
                sttrMap.put(storeProductAttrValue.getSelfSourceSkuId(), storeProductAttrValue);
            }
            if (sttrMap.size() == 1){
                updateStock(attrValueList.get(0),warehouseStock);
                continue;
            }
            if (sttrMap.size()>3){
                log.error(selfSkuId+":此编号异常，请关注。");
                continue;
            }
            int size = sttrMap.size();
            int stock1 = (int) Math.round(warehouseStock * 0.2);
            int stock2 = (int) Math.round((warehouseStock - stock1) * 0.6);
            if (size == 2){
                stock2 = warehouseStock - stock1;
            }
            int stock3 = warehouseStock - stock1 - stock2;
            for (Map.Entry<String, StoreProductAttrValue> entry : sttrMap.entrySet()) {
                String key = entry.getKey();
                StoreProductAttrValue value = entry.getValue();
                String[] split = key.split(selfSkuId);
                if (split.length == 0){
                    updateStock(value,stock1);
                    continue;
                }
                int i = Integer.parseInt(split[1]);
                if (i == 6){
                    updateStock(value,stock2);
                    continue;
                }
                if (i == 12){
                    updateStock(value,stock3);
                }
            }
            relationService.updateById(relation);
        }
    }
    private void updateStock(StoreProductAttrValue storeProductAttrValue,Integer warehouseStock) {
//        Integer totalStock = storeProductAttrValue.getTotalStock() == null ? 0:storeProductAttrValue.getTotalStock();
        Integer groupStock = storeProductAttrValue.getGroupStock() == null ? 0 : storeProductAttrValue.getGroupStock();
        Integer stock = storeProductAttrValue.getStock();
        Integer totalStock = groupStock+stock;
        if (StringUtils.isBlank(storeProductAttrValue.getFeature("attrGroupStock"))){
            storeProductAttrValue.addFeature("attrGroupStock",String.valueOf(groupStock));
            storeProductAttrValue.addFeature("attrStock",String.valueOf(stock));
            storeProductAttrValue.addFeature("attrTotalStock", String.valueOf(totalStock));
        }
        StoreProduct storeProduct = storeProductService.getById(storeProductAttrValue.getProductId());
        if (StringUtils.isBlank(storeProduct.getFeature("productStock"))){
            storeProduct.addFeature("productStock",String.valueOf(storeProduct.getStock()));
        }
        Integer productStock = storeProduct.getStock();
        // 商品库存 = 商品库存 - 当前sku库存 + 查询到的sku库存
        productStock = productStock- totalStock + warehouseStock;
        storeProduct.setStock(productStock);
        // 仓库库存小于团购库存，不处理
        if (warehouseStock <= groupStock){
            return;
        }
        storeProductService.updateById(storeProduct);
        storeProductAttrValue.setTotalStock(warehouseStock);
        storeProductAttrValue.setStock(warehouseStock - groupStock);
        storeProductAttrValueService.updateById(storeProductAttrValue);

    }
//    @XxlJob("junMengStockSync")
    public void stockSync(){
        StoreProductQueryDto storeProductQueryDto = new StoreProductQueryDto();
        storeProductQueryDto.setSupplierIds(new ArrayList<>(MAP.keySet()));
        List<StoreProduct> storeProducts = storeProductDao.selectNeedUpdateStockProducts(storeProductQueryDto);
        if (CollectionUtils.isEmpty(storeProducts)){
            return;
        }
        List<Integer> productsIds = new ArrayList<>();
        Map<Integer, String> pushCodeMap = new HashMap<>();
        for (StoreProduct storeProduct : storeProducts) {
            productsIds.add(storeProduct.getId());
            pushCodeMap.put(storeProduct.getId(), MAP.get(storeProduct.getSuppliersId()));
        }
        List<StoreProductAttrValue> productAttrValues = storeProductAttrValueService.list(Wrappers.<StoreProductAttrValue>lambdaQuery()
                .in(StoreProductAttrValue::getProductId, productsIds));
        if (CollectionUtils.isEmpty(productAttrValues)){
            return;
        }
        Iterator<StoreProductAttrValue> iterator = productAttrValues.iterator();
        Map<String, List<StoreProductAttrValue>> pushMap = new HashMap<>();
        while (iterator.hasNext()){
            StoreProductAttrValue attrValue = iterator.next();
            // 小于八位的算异常数据
            if (StringUtils.isBlank(attrValue.getSelfSourceSkuId()) || attrValue.getSelfSourceSkuId().length() < 8){
                iterator.remove();
                continue;
            }
            String pushCode = pushCodeMap.get(attrValue.getProductId());
            if (StringUtils.isBlank(pushCode)){
                iterator.remove();
                continue;
            }
            pushMap.computeIfAbsent(pushCode, v->new ArrayList<>()).add(attrValue);
        }
        if (MapUtils.isEmpty(pushMap)){
            return;
        }
        for (Map.Entry<String, List<StoreProductAttrValue>> entry : pushMap.entrySet()) {
            String key = entry.getKey();
            List<StoreProductAttrValue> value = entry.getValue();
            String serviceName = SERVICE_MAP.get(key);
            if (StringUtils.isBlank(serviceName)){
                continue;
            }
            List<List<StoreProductAttrValue>> partition = ListUtils.partition(value, 20);
            for (List<StoreProductAttrValue> storeProductAttrValues : partition) {
                String selfSourceSkuIdStr = storeProductAttrValues.stream().map(k->{
                    String selfSourceSkuId = k.getSelfSourceSkuId();
                    if (!selfSourceSkuId.startsWith(key)){
                        return key+selfSourceSkuId;
                    }
                    return selfSourceSkuId;
                }).collect(Collectors.joining(","));
                CommonStoreOrderService serviceInstance = pushWarehouseFactory.getServiceInstance(serviceName);
                CommonResult<List<WarehouseResultData>> listCommonResult = serviceInstance.queryOrderStockInfo(selfSourceSkuIdStr);
                List<WarehouseResultData> warehouseResultDataList = listCommonResult.getData();
                if (CollectionUtils.isEmpty(warehouseResultDataList)){
                    continue;
                }

            }

        }
        System.out.println();


    }
}
